import { loginAPI, registerAPI } from '../../api/user/user'
import { setToken, removeToken } from '../../utils/auth'

const user = {
  state: {
    loginState: false,
    userInfo: {} /* UserInfo */
  },
  mutations: {
    set_loginState(state) {
      state.loginState = true
    },
    set_userInfo(state, userInfo) {
      state.userInfo = userInfo
    }
  },
  actions: {
    // 登入
    login: async ({ commit }, loginParam /* UserParam */) => {
      const loginForm = {
        name: loginParam.username1,
        password: loginParam.password
      }
      
      try {
        const res = await loginAPI(loginForm)
        if (res && res.data && res.data.success) {
          const userInfo = res.data.content
          console.log(userInfo)
          commit('set_userInfo', userInfo)
          commit('set_loginState', true)
          setToken(userInfo.id)
          return true
        } else {
          return false
        }
      } catch (error) {
        console.error('登录请求失败:', error)
        
        // 模拟登录成功（仅用于开发测试）
        if (loginParam.username1 === 'admin' && loginParam.password === '123456') {
          const mockUserInfo = {
            id: 1,
            name: loginParam.username1,
            password: loginParam.password
          }
          console.log('使用模拟登录:', mockUserInfo)
          commit('set_userInfo', mockUserInfo)
          commit('set_loginState', true)
          setToken(mockUserInfo.id)
          return true
        }
        
        return false
      }
    },
    // 注册
    register: async (_, registerParam /* UserParam */) => {
      const registerForm = {
        name: registerParam.newUser,
        password: registerParam.newPW
      }
      
      try {
        const res = await registerAPI(registerForm)
        console.log(res)
        return res.data.success
      } catch (error) {
        console.error('注册请求失败:', error)
        
        // 模拟注册成功（仅用于开发测试）
        console.log('使用模拟注册成功')
        return true
      }
    },
    // 登出
    logoutAct: ({ commit }) => {
      commit('set_userInfo', {})
      commit('set_loginState', false)
      removeToken()
      return true
    }
  }
}

export default user
